/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.thinktank.service;

import cn.hutool.core.util.RandomUtil;
import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.activity.domain.dto.ActivityQueryCriteria;
import com.fzhucc.modules.requirement.domain.Requirement;
import com.fzhucc.modules.requirement.repository.RequirementRepository;
import com.fzhucc.modules.security.config.bean.LoginProperties;
import com.fzhucc.modules.security.config.bean.SecurityProperties;
import com.fzhucc.modules.security.domain.OnlineUser;
import com.fzhucc.modules.security.domain.bo.WxAuthenticationToken;
import com.fzhucc.modules.security.domain.dto.AuthDto;
import com.fzhucc.modules.security.domain.dto.JwtUserDto;
import com.fzhucc.modules.security.security.TokenProvider;
import com.fzhucc.modules.security.service.AuthenticationService;
import com.fzhucc.modules.security.service.OnlineUserService;
import com.fzhucc.modules.security.service.UserDetailsServiceImpl;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.UserService;
import com.fzhucc.modules.thinktank.domain.Leader;
import com.fzhucc.modules.thinktank.domain.dto.*;
import com.fzhucc.modules.thinktank.repository.LeaderRepository;
import com.fzhucc.modules.thinktank.service.mapstruct.LeaderMapper;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author Woolsen
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-11-14
 **/
@Service
@RequiredArgsConstructor
public class LeaderService {

    private final LeaderRepository leaderRepository;

    private final RequirementRepository requirementRepository;
    private final LeaderMapper leaderMapper;

    private final WxClient wxClient;

    private final RedisUtils redisUtils;

    private final UserDetailsServiceImpl userDetailsService;

    private final UserRepository userRepository;

    private final AuthenticationService authenticationService;

    private final UserService userService;

    private final TokenProvider tokenProvider;

    private final OnlineUserService onlineUserService;

    private final SecurityProperties securityProperties;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Resource
    private LoginProperties loginProperties;

    public Map<String, Object> queryAll(LeaderQueryCriteria criteria, Pageable pageable) {
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<Leader> page = leaderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<LeaderDto> map = page.map(leaderMapper::toDto);
        List<LeaderDto> list = map.getContent();
        if (list != null) {
            for (LeaderDto leaderDto : list) {
                Long leaderId = leaderDto.getId();
                List<Requirement> res = requirementRepository.findByThinktankId(leaderId);
                leaderDto.setList(res);
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(LeaderQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null  && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return null;
            }
            if (res.getOrgArea().contains(";")) {
                String[] split = res.getOrgArea().split(";");
                if (split.length == 2) {
                    return split[1];
                } else if (split.length == 3) {
                    return split[1];
                } else if (split.length == 1) {
                    return split[0];
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw new BadRequestException("未符合规范的地区区域");
            }
        }
    }

    public List<LeaderDto> queryAll(LeaderQueryCriteria criteria) {
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return leaderMapper.toDto(leaderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public LeaderDto findById(Long id) {
        Leader leader = leaderRepository.findById(id).orElseGet(Leader::new);
        ValidationUtil.isNull(leader.getId(), "Leader", "id", id);
        return leaderMapper.toDto(leader);
    }

    @Transactional(rollbackFor = Exception.class)
    public LeaderDto create(Leader resources) {
        resources.setIsDelete(false);
        //调整为登录账号为哪个市的添加哪个市
        resources.setOrgArea(orgAreaReturn());
        return leaderMapper.toDto(leaderRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(Leader resources) {
        Leader leader = leaderRepository.findById(resources.getId()).orElseGet(Leader::new);
        ValidationUtil.isNull(leader.getId(), "Leader", "id", resources.getId());
        leader.copy(resources);
        //调整为登录账号为哪个市的添加哪个市
        leader.setOrgArea(orgAreaReturn());
        leaderRepository.save(leader);
    }

    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            //leaderRepository.deleteById(id);
            Optional<Leader> res = leaderRepository.findById(id);
            if (!res.isPresent()) {
                throw new BadRequestException("未找到产业龙头");
            }
            Leader leader = res.get();
            leader.setIsDelete(true);
            leaderRepository.save(leader);
        }
    }

    public void download(List<LeaderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LeaderDto leader : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("描述", leader.getDescription());
            map.put("名称", leader.getName());
            map.put("图片链接", leader.getPhoto());
            map.put("排序", leader.getSort());
            map.put("区域划分", leader.getOrgArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 生成产业龙头绑定码。绑定码有效时间：1天
     *
     * @param leaderId 产业龙头ID
     * @return AllBindDto
     */
    public AllBindDto generateQrCode(Long leaderId) {
        if (!leaderRepository.existsById(leaderId)) {
            throw new BadRequestException("产业龙头[id:" + leaderId + "]不存在");
        }
        String code = RandomUtil.randomString(10);
        String qrcode = wxClient.generateMpQr(
                null,
                "type=bindLt&code=" + code
        );
        String url = wxClient.generateUrlLink(
                null,
                "type=bindLt&code=" + code,
                86400000L
        );
        redisUtils.set("leader:bind:" + code, leaderId, 86400);
        AllBindDto dto = new AllBindDto();
        dto.setExpireTime(86400000L);
        dto.setQrcode(qrcode);
        dto.setUrl(url);
        return dto;
    }

    public LeaderDto findLeaderByCode(String code) {
        Long leaderId = (Long) redisUtils.get("leader:bind:" + code);
        if (leaderId == null) {
            throw new BadRequestException("产业龙头邀请码不存在");
        }
        final Leader leader = leaderRepository.findById(leaderId).orElseThrow(() ->
                new BadRequestException("产业龙头[id:" + leaderId + "]不存在")
        );
        return leaderMapper.toDto(leader);
    }

    @Transactional
    public AuthDto bindLeader(AllBindDto2 dto, HttpServletRequest request) {
        Long leaderId = (Long) redisUtils.get("leader:bind:" + dto.getCode());
        if (leaderId == null) {
            throw new BadRequestException("产业龙头邀请码不存在");
        }
        JwtUserDto currentUser;
        try {
            currentUser = userDetailsService.loadUserByUsername(JwtSecurityUtils.getCurrentUsername());
            final Long userId = currentUser.getUser().getId();
            // 若已绑定其他产业龙头，则先取消原先绑定的产业龙头
            Leader leader = leaderRepository.findByUserId(userId);
            if (leader != null) {
                leader.setUserId(null);
                leaderRepository.save(leader);
            }
        } catch (UsernameNotFoundException e) {
            // 用户未登录，则走登录流程
            if (dto.getWxCode() == null) {
                throw new BadRequestException("用户信息未找到");
            }
            WxAuthenticationToken wxAuthentication = authenticationService.authenticateByWxMpCode(dto.getWxCode(), 5);
            currentUser = wxAuthentication.getUser();
        }
        Leader leader = leaderRepository.findById(leaderId).orElseThrow(() ->
                new BadRequestException("产业龙头[id:" + leaderId + "]不存在")
        );
        Long currentUserId = currentUser.getUser().getId();
        leader.setUserId(currentUserId);
        leaderRepository.save(leader);
        if (currentUser.getUser().getRoles().stream().noneMatch(s -> s.getId() == 5)) {
            userService.grantRole(currentUserId, 5L);
        }
        redisUtils.del("leader:bind:" + dto.getCode());

        // 权限修改，返回新的token
        User user = userRepository.findByUsername(currentUser.getUsername());
        WxAuthenticationToken authentication = authenticationService.authenticateByUnionId(user.unionId);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String apiToken = tokenProvider.createToken(authentication);
        JwtUserDto jwtUserDto = authentication.getPrincipal();
        // 保存在线信息
        onlineUserService.save(jwtUserDto, OnlineUser.SYSTEM, apiToken, request);
        // 返回 token 与 用户信息
        AuthDto authDto = new AuthDto(
                securityProperties.getTokenStartWith() + apiToken,
                jwtUserDto
        );
        if (loginProperties.isSingleLogin()) {
            //踢掉之前已经登录的token
            onlineUserService.checkLoginOnUser(authDto.getUser().getUsername(), apiToken);
        }
        return authDto;
    }

    public List<Leader> getExpertInfoByListId(Long[] expertIds) {
        List<Leader> list = new ArrayList<Leader>();
        if (expertIds == null) {
            throw new BadRequestException("产业龙头专家ListId未找到");
        }
        for (Long id : expertIds) {
            Optional<Leader> res = leaderRepository.findById(id);
            if (res.isPresent()) {
                list.add(res.get());
            }
        }
        return list;
    }
}